<?php
/**
 * Joomla! 1.5 component JoomGPSTracks
 *
 * @version $Id: cat.php 2009-06-24 15:40:19 svn $
 * @author Michael Pfister
 * @package joomGPStracks
 * @subpackage backend
 * @license GNU/GPL
 * @filesource
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

/**
 * Model Class Categorie
 */
class JoomgpstracksModelCat extends JModel  {

	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid', array(0), '', 'array');
		$edit	= JRequest::getVar('edit',true);
		if($edit)
			$this->setId((int)$array[0]);
	}

    /**
     *
     * @param int $id
     */
	function setId($id)
	{
		// Set weblink id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}

    /**
     *
     * @param string $direction
     * @return boolean
     */
	function move($direction)
	{
		$row =& $this->getTable('gps_cats');
		if (!$row->load($this->_id)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->move( $direction )) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;
	}

    /**
     *
     * @param array $cid
     * @param string $order
     * @return boolean
     */
	function saveorder($cid = array(), $order)
	{
		$row =& $this->getTable('gps_cats');
		$groupings = array();

		// update ordering values
		for( $i=0; $i < count($cid); $i++ )
		{
			$row->load( (int) $cid[$i] );
			// track categories
			$groupings[] = $row->catid;

			if ($row->ordering != $order[$i])
			{
				$row->ordering = $order[$i];
				if (!$row->store()) {
					$this->setError($this->_db->getErrorMsg());
					return false;
				}
			}
		}


		// execute updateOrder for each parent group
		$groupings = array_unique( $groupings );
		foreach ($groupings as $group){
			$row->reorder('id = '.(int) $group);
		}

		return true;
	}

    /**
     *
     * @param array $cid
     * @param int $publish
     * @return boolean
     */
	function publish($cid = array(), $publish = 1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__gps_cats'
				. ' SET published = '.(int) $publish
				. ' WHERE id IN ( '.$cids.' )'
				. ' AND ( checked_out = 0 OR ( checked_out = '.(int) $user->get('id').' ) )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

    /**
     *
     * @param array $cid
     * @return boolean
     */
	function delete($cid = array())
	{
        jimport('joomla.filesystem.file');

		$result = false;

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
            // delete the images
            $query = "SELECT * FROM #__gps_cats"
                    . "\n WHERE id IN ( '.$cids.' )";

            $this->_db->setQuery($query);
            $rows = $this->_db->loadObjectList();

            if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}

            foreach($rows as $row)  {
                JFile::delete(JPATH_SITE.DS."images".DS."joomgpstracks".DS."cats".DS.$row->image);
            }

            //delete from DB
			$query = 'DELETE FROM #__gps_cats'
				. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

    /**
     *
     * @global obejct $mainframe
     * @return boolean
     */
    function saveCat()  {
        global $mainframe;

        // check the token
        JRequest::checkToken() or die( 'Invalid Token' );
        jimport('joomla.filesystem.file');

        $db =& JFactory::getDBO();

        $file =& JRequest::getVar('image', null, 'files', 'array');
        $title =& JRequest::getVar( 'title' );
        $published =& JRequest::getInt( 'publish' );
        $desc =& JRequest::getVar( 'desc', '', 'post', 'string', JREQUEST_ALLOWRAW);
        $parent =& JRequest::getInt('parent');

        // image upload part
        $upload_dir = JPATH_SITE.DS."images".DS."joomgpstracks".DS."/cats".DS.$name;
        $filename = JFile::makeSafe($file['name']);
        if(file_exists($filename)):
            if (!JFile::upload($file['tmp_name'], $upload_dir.strtolower($filename))) {
                JError::raiseWarning('SOME_ERROR_CODE', JText::_('GPS_UPLOAD_FAILED'));
                return false;
            } else {
                JError::raiseNotice('SOME_ERROR_CODE', JText::_('GPS_UPLOAD_COMPLET'));
            }
        endif;

        $query = "INSERT INTO #__gps_cats SET"
                . "\n parent='".$parent."',"
                . "\n title='" . $title . "',"
                . "\n description='" . $desc . "',"
                ;
        if($filename) {
            $query .= "\n image='" . $filename . "',";
        }

        $query .= "\n published='" . $published . "'";

        $db->setQuery($query);
        $db->query();

        if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}

        return true;
    }

    /**
     *
     * @global object $mainframe
     * @return boolean
     */
    function updateCat()  {
        global $mainframe;

        // check the token
        JRequest::checkToken() or die( 'Invalid Token' );
        jimport('joomla.filesystem.file');

        $db =& JFactory::getDBO();

        $id =& JRequest::getInt('id');
        $file =& JRequest::getVar('image', null, 'files', 'array');
        $title =& JRequest::getVar( 'title' );
        $published =& JRequest::getInt( 'publish' );
        $desc =& JRequest::getVar( 'desc', '', 'post', 'string', JREQUEST_ALLOWRAW);
        $parent =& JRequest::getInt('parent');

        // image upload part
        if($file != null)  {
            $upload_dir = JPATH_SITE.DS."/images/joomgpstracks/cats/" . $name;
            $filename = JFile::makeSafe($file['name']);
            if(file_exists($filename)):
                if (!JFile::upload($file['tmp_name'], $upload_dir.strtolower($filename))) {
                    JError::raiseWarning('SOME_ERROR_CODE', JText::_('GPS_UPLOAD_FAILED'));
                    return false;
                } else {
                    JError::raiseNotice('SOME_ERROR_CODE', JText::_('GPS_UPLOAD_COMPLET'));
                }
            endif;
        }

        $query = "UPDATE #__gps_cats SET"
                . "\n parent='".$parent."',"
                . "\n title='" . $title . "',"
                . "\n description='" . $desc . "',"
                ;
        if($filename) {
            $query .= "\n image='" . $filename . "',";
        }

        $query .= "\n published='" . $published . "'";
        $query .= "\n WHERE id='" . $id . "'";

        $db->setQuery($query);
        $db->query();

        if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}

        return true;
    }


}
?>
